package com.xhs.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhs.dto.*;
import com.xhs.model.QrCodeResult;
import com.xhs.model.SearchTask;
import com.xhs.model.User;
import com.xhs.manager.QrCodeResultManager;
import com.xhs.manager.SearchTaskManager;
import com.xhs.manager.UserManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 执行结果控制器
 *
 * @author xhs
 */
@Slf4j
@RestController
@RequestMapping("/api/result")
@Tag(name = "执行结果管理", description = "二维码扫描结果管理相关接口")
public class ResultController {

    @Autowired
    private QrCodeResultManager qrCodeResultManager;

    @Autowired
    private SearchTaskManager searchTaskManager;

    @Autowired
    private UserManager userManager;

    /**
     * 获取结果列表
     */
    @Operation(summary = "获取结果列表", description = "获取当前用户的所有扫描结果")
    @PostMapping("/list")
    public XhsResponse<List<QrCodeResult>> getResultList(@Valid @RequestBody ResultListRequest request) {
        log.info("获取结果列表请求: phoneNumber={}", request.getPhoneNumber());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        List<QrCodeResult> results = qrCodeResultManager.findByUserId(user.getId());
        return XhsResponse.success("获取结果列表成功", results);
    }

    /**
     * 分页获取结果列表
     */
    @Operation(summary = "分页获取结果列表", description = "分页获取当前用户的扫描结果")
    @PostMapping("/page")
    public XhsResponse<IPage<QrCodeResult>> getResultPage(@Valid @RequestBody ResultListRequest request) {
        log.info("分页获取结果列表请求: phoneNumber={}, pageNum={}, pageSize={}", 
                request.getPhoneNumber(), request.getPageNum(), request.getPageSize());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        IPage<QrCodeResult> resultPage = qrCodeResultManager.findByUserIdWithPage(
                user.getId(), request.getPageNum(), request.getPageSize());
        return XhsResponse.success("获取结果列表成功", resultPage);
    }

    /**
     * 根据任务获取结果
     */
    @Operation(summary = "根据任务获取结果", description = "获取指定任务的扫描结果")
    @PostMapping("/by-task")
    public XhsResponse<List<QrCodeResult>> getResultsByTask(@Valid @RequestBody ResultByTaskRequest request) {
        log.info("根据任务获取结果请求: phoneNumber={}, taskId={}", 
                request.getPhoneNumber(), request.getTaskId());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 查询任务
        SearchTask task = searchTaskManager.getById(request.getTaskId());
        if (task == null) {
            return XhsResponse.error("任务不存在");
        }

        // 检查任务是否属于当前用户
        if (!task.getUserId().equals(user.getId())) {
            return XhsResponse.error("无权限访问此任务结果");
        }

        List<QrCodeResult> results = qrCodeResultManager.findByTaskId(Long.valueOf(request.getTaskId()));
        return XhsResponse.success("获取任务结果成功", results);
    }

    /**
     * 根据任务分页获取结果
     */
    @Operation(summary = "根据任务分页获取结果", description = "分页获取指定任务的扫描结果")
    @PostMapping("/task/page")
    public XhsResponse<IPage<QrCodeResult>> getResultsByTaskPage(@Valid @RequestBody ResultByTaskRequest request) {
        log.info("根据任务分页获取结果请求: phoneNumber={}, taskId={}, pageNum={}, pageSize={}", 
                request.getPhoneNumber(), request.getTaskId(), request.getPageNum(), request.getPageSize());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 查询任务
        SearchTask task = searchTaskManager.getById(Long.valueOf(request.getTaskId()));
        if (task == null) {
            return XhsResponse.error("任务不存在");
        }

        // 检查任务是否属于当前用户
        if (!task.getUserId().equals(user.getId())) {
            return XhsResponse.error("无权限访问此任务结果");
        }

        IPage<QrCodeResult> resultPage = qrCodeResultManager.findByTaskIdWithPage(
                Long.valueOf(request.getTaskId()), request.getPageNum(), request.getPageSize());
        return XhsResponse.success("获取任务结果成功", resultPage);
    }

    /**
     * 根据任务名称获取结果
     */
    @Operation(summary = "根据任务名称获取结果", description = "获取指定任务名称的扫描结果")
    @PostMapping("/by-task-name")
    public XhsResponse<List<QrCodeResult>> getResultsByTaskName(@Valid @RequestBody ResultByTaskNameRequest request) {
        log.info("根据任务名称获取结果请求: phoneNumber={}, taskName={}", 
                request.getPhoneNumber(), request.getTaskName());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 使用分页查询但获取所有结果
        IPage<QrCodeResult> resultPage = qrCodeResultManager.findByTaskNameWithPage(
                user.getId(), request.getTaskName(), 1, 10000);
        List<QrCodeResult> results = resultPage.getRecords();
        return XhsResponse.success("获取任务结果成功", results);
    }

    /**
     * 搜索结果
     */
    @Operation(summary = "搜索结果", description = "根据关键词搜索扫描结果")
    @PostMapping("/search")
    public XhsResponse<List<QrCodeResult>> searchResults(@Valid @RequestBody ResultSearchRequest request) {
        log.info("搜索结果请求: phoneNumber={}, keyword={}", 
                request.getPhoneNumber(), request.getKeyword());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        List<QrCodeResult> results = qrCodeResultManager.findByKeyword(
                user.getId(), request.getKeyword());
        return XhsResponse.success("搜索结果成功", results);
    }

    /**
     * 获取时间范围内的结果
     */
    @Operation(summary = "获取时间范围结果", description = "获取指定时间范围内的扫描结果")
    @PostMapping("/time-range")
    public XhsResponse<List<QrCodeResult>> getResultsByTimeRange(@Valid @RequestBody ResultTimeRangeRequest request) {
        log.info("获取时间范围结果请求: phoneNumber={}, startTime={}, endTime={}", 
                request.getPhoneNumber(), request.getStartTime(), request.getEndTime());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        List<QrCodeResult> results = qrCodeResultManager.findByTimeRange(
                user.getId(), request.getStartTime(), request.getEndTime());
        return XhsResponse.success("获取时间范围结果成功", results);
    }

    /**
     * 获取结果统计
     */
    @Operation(summary = "获取结果统计", description = "获取用户的扫描结果统计信息")
    @PostMapping("/statistics")
    public XhsResponse<Map<String, Object>> getStatistics(@Valid @RequestBody ResultStatisticsRequest request) {
        log.info("获取结果统计请求: phoneNumber={}", request.getPhoneNumber());

        // 查询用户
        User user = userManager.findByPhoneNumber(request.getPhoneNumber());
        if (user == null) {
            return XhsResponse.error("用户不存在");
        }

        // 获取统计信息
        long totalCount = qrCodeResultManager.countByUserId(user.getId());
        Map<String, Object> statistics = java.util.Map.of("totalCount", totalCount);
        return XhsResponse.success("获取统计信息成功", statistics);
    }

} 